<?php

namespace forfun\service;

use forfun\constant\ErrorCode;
use forfun\controller\vo\UserForm;
use forfun\repository\entity\User;
use forfun\repository\UserRepository;
use restphp\http\request\RestHttpRequestIP;
use restphp\utils\RestUUIDUtil;
use Sofical\Restphp\exception\BaException;

class UserService {
    /**
     * 获取用户，如果不存在，则创建.
     * @param UserForm $userForm
     * @return User
     */
    public static function getUserOrRegister($userForm) {
        $userRepository = new UserRepository();
        $user = $userRepository->findOne(array(
            'nickname' => $userForm->getNickname()
        ));
        if (null == $user) {
            // 如果用户不存在，检查是否可以创建
            $deviceUser = $userRepository->findOne(array(
                'device_code' => $userForm->getDeviceCode()
            ));
            if (null != $deviceUser) {
                // 不可创建
                throw new BaException(ErrorCode::USER_DEVICE_CODE_EXISTED);
            }

            $user = new User();
            $user->setNickname($userForm->getNickname());
            $user->setPwd(md5($userForm->getPwd()));
            $user->setDeviceCode($userForm->getDeviceCode());
            $user->setRegisterIp(RestHttpRequestIP::getAgentIp());
            $user->setCreateTime(date('Y-m-d H:i:s'));
        }
        if (md5($userForm->getPwd()) != $user->getPwd()) {
            throw new BaException(ErrorCode::USER_PWD_ERROR);
        }
        $user->setLoginToken(RestUUIDUtil::guid());
        $userRepository->save($user);
        return $user;
    }

    /**
     * 根据token获取用户.
     * @param $loginToken
     * @return mixed|null
     */
    public static function getUserByToken($loginToken) {
        $userRepository = new UserRepository();
        return $userRepository->findOne(array(
            'login_token' => $loginToken
        ));
    }

    /**
     * 获取用户名map.
     * @param $arrIds
     * @return array
     */
    public static function getUsernameMapByIds($arrIds) {
        if (empty($arrIds)) {
            return array();
        }
        $userQueryRule = array(
            'id' => array('id in (:user_id)', array('user_id'=>$arrIds))
        );
        $userRepository = new UserRepository();
        $userList = $userRepository->findAll($userQueryRule);
        $userNameMap = array();
        foreach ($userList as $user) {
            $userNameMap[$user->getId()] = $user->getNickname();
        }
        return $userNameMap;
    }
}